<?php
/**
 * 文件删除处理
 */

require_once 'config/config.php';
require_once 'includes/db.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => '无效的请求方法']);
    exit;
}

// 检查是否已安装
if (!file_exists(__DIR__ . '/config/installed.lock')) {
    echo json_encode(['success' => false, 'message' => '系统未安装，请先运行安装程序']);
    exit;
}

try {
    // 验证CSRF令牌
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        throw new Exception('安全验证失败');
    }

    // 接收参数
    $fileId = intval($_POST['id'] ?? 0);
    $deleteCode = trim($_POST['delete_code'] ?? '');

    if ($fileId <= 0 || empty($deleteCode)) {
        throw new Exception('参数错误');
    }

    // 查询文件信息
    $db = new Database();
    $file = $db->fetchOne("SELECT * FROM files WHERE id = ?", [$fileId]);

    if (!$file) {
        throw new Exception('文件不存在');
    }

    // 验证管理员密码
    if (ADMIN_PASSWORD !== $deleteCode) {
        throw new Exception('管理员密码错误');
    }

    // 删除物理文件
    if (file_exists($file['file_path'])) {
        unlink($file['file_path']);
    }

    // 从数据库删除
    $db->query("DELETE FROM files WHERE id = ?", [$fileId]);

    echo json_encode([
        'success' => true,
        'message' => '删除成功'
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
